﻿(function(){
	if(!localStorage)
	{
		window.alert("您的浏览器不支持该脚本，请使用FF3.5.1以上版本");	
	}
	else{
		
		function initFloatBox()
		{
			$.floatbox = function (options) {
		//support for jquery 1.0 request by christoph@breidert.net
		var getWidth = function () {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var width;
			if (version > 1) {
				width = $(window).width();
			} else {
				width = document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth;
			}
			return width / 2;
		};
		
		var getHeight = function () {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var height;
			if (version > 1) {
				height = $(window).height();
			} else {
				height = document.body.scrollHeight ? document.body.scrollHeight : document.documentElement.scrollheight;
			}
			return height;
		};
		
		var settings = $.extend(true, {
			bg : "floatbox-background",
			box : "floatbox-box",
			content : "",
			button: "<p><a role='button' href='javascript:void(0);' class='close-floatbox'>Close</a></p>",
			desc: "This is a popup box, press esc key to close.",
			fade : false,
			ajax: null,
			buttonPosition: "bellow",
			bgConfig : {
				position: ($.browser.msie) ? "absolute" : "fixed",
				zIndex: 8,
				width: "100%",
				height: "100%",
				top:  "0px",
				left: "0px",
				backgroundColor: "#000",
				opacity: "0.75",
				display: "none"
			},
			boxConfig : {
				position : ($.browser.msie) ? "absolute" : "fixed",
				zIndex: 9,
				width: getWidth() + "px",
				marginLeft: "-" + (getWidth() / 2) + "px",
				height: "50%",
				top: "0px",
				left: "50%",
				backgroundColor: "transparent",
				display: "none",
			}
		}, options);
		
		//hidden div containing all settings
		$("<div></div>")
		.attr("id", "jqfloatbox-params")
		.css("display", "none")
		.appendTo("body")
		.each(function () {
			$.data(this, settings);
		});

		//inserts floatbox and sets its content
		var showBox = function () {
			var content = typeof settings.content === "string" ? settings.content : settings.content.clone();
			//inserts the background element in the document
			$("<div></div>")
				.bind("click", function () {
					closeBox();
				})
				.attr("id", settings.bg)
				.css(settings.bgConfig)
				.width(($.browser.msie) ? document.body.clientWidth : "100%")
				.height(($.browser.msie) ? document.body.clientHeight : "100%")
				.appendTo("body");
			//inserts the floating box in the document
			$("<div></div>")
				.attr({id: settings.box, role: "alertdialog"})
				.appendTo("body")
				.each(function () {
					if (settings.buttonPosition == "bellow") {
						$(this)
						.html(content)
						.append(settings.button);
					} else if (settings.buttonPosition == "above") {
						$(this)
						.empty()
						.append(settings.button)
						.append(content);
					} else {
						$(this)
						.html(content);
					}
				})
				.css(settings.boxConfig)
				.css("margin-top", $("#" + settings.box).height() > getHeight() ? "0" :  "-" + $("#" + settings.box).height() / 2 + "px")
				.css("top",  $("#" + settings.box).height() > getHeight() ? "0" :  "50%")
				.css("position", $("#" + settings.box).height() > getHeight() ? "absolute" :  ($.browser.msie) ? "absolute" : "fixed")
				.find(".close-floatbox").bind("click", function () {
					closeBox();
				})
				.end();
			//checks if it needs to fade or not
			if (settings.fade) {
				$("#" + settings.bg)
				.fadeIn(200, function () {
					$("div#" + settings.box).fadeIn(200);
				});
			} else {
				$("#" + settings.bg)
				.show()
				.parent().find("#" + settings.box).show();
			}
			//sets if ajax is needed(already detectets if it is POST or GET)
			if (settings.ajax) {
				$.ajax({
					type: settings.ajax.params === "" ? "GET" : "POST",
					url: settings.ajax.url,
					data: settings.ajax.params,
					
					beforeSend: function () {
						$("#" + settings.box).html(settings.ajax.before);
					},
					
					success: function (data) {
						$("#" + settings.box)
							.html(data)
							.append(settings.button)
							.find(".close-floatbox").bind("click", function () {
								closeBox()
							})
						.end();
						
					},
					complete: function (XMLHttpRequest, textStatus) {
						if (settings.ajax.finish) {
							settings.ajax.finish(XMLHttpRequest, textStatus);
						}
					},
					contentType: "html"
				});
			}
		};
		//hides floatingbox and background
		var closeBox = function () {
			if (settings.fade) {
				$("#" + settings.box).fadeOut(200, function () {
					 $("#" + settings.bg).fadeOut(200, function () {
						$("#" + settings.box).remove();
						$("#" + settings.bg).remove();
					});
				});
			} else {
				//for opera issues hide first and a timeout is needed to remove the elements
				$("#" + settings.box + ",#" + settings.bg).hide();
				setTimeout(function () {
					$("#" + settings.box).remove();
					$("#" + settings.bg).remove();
				}, 500);
			}
		};
		//inits the floatbox
		var init = function () {
			//shows box
			showBox();
			//adds cross browser event to esc key to hide floating box
			$(document).one("keypress", function (e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			})
			.one("keydown", function (e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			});
			//if msie6, adds event to browser scroll to keep floatbox ina fixed position and uses css hack for full background size
			if ($.browser.msie && $("#" + settings.box).height() > getHeight()) {
				$("body, html").css({height: "100%", width: "100%"});
				$(window).bind("scroll", function () {
					$("#" + settings.box).css("top", document.documentElement.scrollTop +  ($(window).height() / 2) + "px");
				});
			}
		};
		//starts the plugin
		init();
		}
		}

		var b=document.head;
		if(b&&!document.xmlVersion)
		{void(mc=document.createElement('script'));
		void(mc.src='http://code.jquery.com/jquery-1.4.2.min.js');
		void(mc.setAttribute('charset','utf-8'));void(b.appendChild(mc));}else{}


	//构建基本函数库
		function zipIt(){return zipIt};
		
		function insertAfter(newElement, targetElement) 
	{ 
	    var parent = targetElement.parentNode; 
	    if(parent.lastChild == targetElement) 
	    { 
		parent.appendChild(newElement); 
	    } 
	    else 
	    { 
		parent.insertBefore(newElement, targetElement.nextSibling); 
	    } 
	}

	Array.prototype.del=function(n) {
	　if(n<0)
	　　return this;
	　else
	　　return this.slice(0,n).concat(this.slice(n+1,this.length));
	}

	Storage.prototype.setObject = function(key, value) {
	    this.setItem(key, JSON.stringify(value));
	}

	Storage.prototype.getObject = function(key) {
	    return this.getItem(key) && JSON.parse(this.getItem(key));
	}
	//构建基本对象
		//构建全局对象	
		wholeThreads=new Object();
		wholeThreads.threadArray=new Array();
		wholeThreads.headArr=new Array();
		//定义对象
		
		//帖子和主题类

		function singleThread(){
			this.top="undefined";
			this.identify="undefined";
			this.firstDiv="undefined";
			this.contentDiv="undefined";
			this.lastDiv="undefined";
			this.writter="undefined";
			this.writterId="undefined";
			this.showStatus=true;
		};
		singleThread.prototype.triggerShow=function()
		{
			if(this.showStatus==true)
			{
				try{
			this.firstDiv.style.display='none';
			this.contentDiv.style.display='none';
			this.lastDiv.style.display='none';
			//this.top.style.display='none';
			this.showStatus=false;
				}
				catch(error)
				{
					//console.log(error);
				}

			}
			else
			{
				try{
			this.firstDiv.style.display='';
			this.contentDiv.style.display='';
			this.lastDiv.style.display='';
			//this.top.style.display='';
			this.showStatus=true;
				}
				catch(error)
				{
					//console.log(error);
				}
			
			}
		}

		singleThread.prototype.getWritterInfo=function(){
			try{
				var tempInfo=this.contentDiv.childNodes[1].childNodes[1].childNodes[0].childNodes[0].childNodes[1].childNodes[1].childNodes[1].childNodes[3];
			}
			catch(e)
			{
				//console.log(e);
			}
			if(tempInfo&&typeof(tempInfo)!="undefined")
			{
				regex=/uid=(\d+)/;
				this.writterId=regex.exec(tempInfo)[1];
				this.writter=tempInfo.innerHTML;
			}
		}

		function threadHead(){
			this.writter="undefined";
			this.writterId="undefined";
			this.showStatus=true;
			this.head="undefined";
		}
		
		threadHead.prototype.triggerShow=function()
		{
			if(this.showStatus==true)
			{
				try
				{
					this.head.style.display='none';
				}
				catch (error)
				{
					//console.log(error);
				}
				
			}
			else
			{
				try
				{
					this.head.style.display='';
				}
				catch (error)
				{
					//console.log(error);
				}
				
			}
		}

		threadHead.prototype.getWritterInfo=function(){
			var tempInfo=this.head.childNodes[3].firstChild;
			if(tempInfo&&typeof(tempInfo)!="undefined")
			{
				try
				{
					regex=/uid=(\d+)/;
				this.writterId=regex.exec(tempInfo)[1];
				this.writter=tempInfo.innerHTML;
				}
				catch (error)
				{
					//console.log("获取用户信息错误");
				}
			}
		}

		//构建用户类

		function User(){
		this.userId="undefined";
		this.userName="undefined";
	}

	User.prototype.addIntoBlackList=function()
	{
		var result=this.checkIfExisted();
		if(result&&result!="-1")
		{
			alert("操作错误，该用户已被塞抹布");
		}
		else if(result=="-1")
		{
			try
			{
				var tempArray=localStorage.getObject("blacklist");
			tempArray.push(this);
			localStorage.setObject("blacklist",tempArray);
			location.reload();
			}
			catch (error)
			{
				//console.log("添加用户进黑名单错误");
			}
		}
		else
		{
			try
			{
			var tempArray=new Array();
			tempArray.push(this);
			localStorage.setObject("blacklist",tempArray);
			location.reload();
			}
			catch (error)
			{
				//console.log("添加用户进黑名单错误");
			}
			
		}
	}

	User.prototype.checkIfExisted=function()
	{
		if(localStorage.getObject("blacklist")==null)
		{
		//数据库不存在，未被塞抹布
			return null;
		}
		var existed=null;
		var index="-1";
		var tempArray=localStorage.getObject("blacklist");
		for(var i=0;i<tempArray.length;i++)
		{
			if(tempArray[i].userId==this.userId.toString())
			{
			//该用户存在
				existed=true;
				index=i.toString();
			}
		}
		//数据库存在，但该用户不存在，未被塞抹布
		return index;
	}

	User.prototype.removeFromBlackList=function()
	{
		var result=this.checkIfExisted();
		if(!result||result=="-1")
		{
			alert("操作失误，该用户当前未被塞抹布");
		}
		else
		{
			try
			{
				var existed=false;
			var index=result;
			var tempArray=localStorage.getObject("blacklist");
			tempArray=tempArray.del(index);
			localStorage.setObject("blacklist",tempArray);
			location.reload();
			}
			catch (error)
			{
				//console.log("移除数据库错误，请检查localStorage是否可用");
			}	
		}
	}


	//功能函数
	//获取当页全部主题
		function getAllThreadHead(){
			
		var tempArr=$('div[id=div940_2]');

			var headMom=tempArr[tempArr.length-2].firstChild.nextSibling.lastChild.previousSibling;
			var nowChild=headMom.firstChild.nextSibling.nextSibling.nextSibling.nextSibling;
			while(nowChild && typeof(nowChild)!="undefined")
				{
				//第一页会出现问题，暂时解决方案
					if(typeof(nowChild.childNodes[3])=="undefined")
					{
						try
						{
							nowChild=nowChild.nextSibling.nextSibling;
						}
						catch (error)
						{
							//console.log("获取"+nowChild+"节点时出现错误");
						}
						
					}
					else
					{
					var tempHead=new threadHead();
					tempHead.head=nowChild;
					tempHead.getWritterInfo();
					wholeThreads.headArr.push(tempHead);
					nowChild=nowChild.nextSibling.nextSibling;
					}
				}
		
		}
		
		//获取当页全部回复
		function getAllReply()
		{
			var basicArr=$('.tiptop').parents('#div940_2').prev('#div940_1');
            var sThread=new singleThread();	
            sThread.identify="tpc";
			sThread.firstDiv=basicArr[0];
			sThread.contentDiv=$(sThread.firstDiv).next('#div940_2')[0];
            sThread.lastDiv=$(sThread.contentDiv).next('#div940_3')[0];            
            sThread.getWritterInfo();
            wholeThreads.threadArray.push(sThread);
            	for(var i=1;i<basicArr.length;i++)
                	{
                    ////console.log(tempArray[i]);
                    try
                    {
                    var sThread=new singleThread();	
                    sThread.identify=basicArr[i];
                    sThread.firstDiv=basicArr[i];
					sThread.contentDiv=$(sThread.firstDiv).next('#div940_2')[0];
            		sThread.lastDiv=$(sThread.firstDiv).next('#div940_3')[0];                     
                    sThread.getWritterInfo();
                    wholeThreads.threadArray.push(sThread);
                    }
                    catch (error)
                    {
                        //console.log("获取第"+i.toString()+"个回复节点时出现错误");
                    }
                }                    
                            
           
			
		}

	//主题页检测是否有屏蔽用户
	function checkBlackListedHead()
		{
			var tempList=localStorage.getObject('blacklist');
			if(""==tempList)
			{
				//alert("数据库错误，请手动清空localStorage后再尝试");
			}
			if(tempList)
			{
			for(var i=0;i<wholeThreads.headArr.length;i++)
			{
				for(var j=0;j<tempList.length;j++)
				{
					if(tempList[j].userId==wholeThreads.headArr[i].writterId)
					{
						try
						{
							wholeThreads.headArr[i].triggerShow();
						}
						catch (error)
						{
							//console.log("检查黑名单错误，请检查数据库");
						}
						
					}
				}
			}
			}
		}

	function checkBlackListedReply()
		{
			var tempList=localStorage.getObject('blacklist');
			if(""==tempList)
			{
				//alert("数据库错误，请手动清空localStorage后再尝试");
			}
			if(tempList)
			{
			for(var i=0;i<wholeThreads.threadArray.length;i++)
			{
				for(var j=0;j<tempList.length;j++)
				{
					if(tempList[j].userId==wholeThreads.threadArray[i].writterId)
					{
						wholeThreads.threadArray[i].triggerShow();
					}
				}
			}
			}
		}
		//获取用户信息
	function getUserInfo()
	{
		user=new User();
		try
		{
			user.userId=document.body.innerHTML.match(/数字账号：(\d+)/)[1];
			var tempName=document.body.innerHTML.match(/用户名称：<b>(.*?)<\/b>/)[1];
			user.userName=tempName;
		}
		catch (error)
		{
			//console.log("获取用户信息错误");
		}
		
		return user;
	}
	//修改用户信息页面
		function modifyProfilePage()
	{
		var tempArr=document.getElementsByTagName("a");
		var insertPoint="";
		for(var i=0;i<tempArr.length;i++)
		{
			regex=/.*sch_area=.*/;
				if(regex.exec(tempArr[i].href))
				{
					insertPoint=tempArr[i];
				}
			
		}
		if(getUserInfo().checkIfExisted()&&getUserInfo().checkIfExisted()!="-1")
		{
			var shutUpPoint=document.createElement("a");
			shutUpPoint.id="zipIt";
			shutUpPoint.href="javascript:zipIt.userInfo().removeFromBlackList()";
			shutUpPoint.innerHTML="[取出抹布]";
			insertAfter(shutUpPoint,insertPoint.nextSibling)
		}
		else
		{
			var shutUpPoint=document.createElement("a");
			shutUpPoint.id="shutUp";
			shutUpPoint.href="javascript:zipIt.userInfo().addIntoBlackList()";
			shutUpPoint.innerHTML="[塞之]";
			insertAfter(shutUpPoint,insertPoint.nextSibling)
		}
	}

		function delFromList(index)
		{
			/*
			var rowId=$(this).parent().attr('id');
			var regex=/row(\d+)/;
			var index=regex.exec(rowId)[1];
			console.log(index);
			*/
			zipIt.blacklist=zipIt.blacklist.del(index);
			traverseList();
		}
	
		function traverseList()
		{
		$('#blackList').empty();
		$('#blackList').append('<tr><td><p>用户名</p></td><td><p>用户ID</p></td><td><p>删除用户</p></td></tr>');
		for(var i=0;i<zipIt.blacklist.length;i++)
			{
			var newRow=$('<tr id="row'+i.toString()+'"></tr>');
			newRow.append('<td class="username"><p>'+zipIt.blacklist[i].userName+'</p></td>');
			newRow.append('<td class="userId"><p>'+zipIt.blacklist[i].userId+'</p></td>');
			//newRow.append('<td class="del_btn"><a href="#">从列表中清除</a>');
			newRow.append('<td class="del_btn"><a href="javascript:window.zipIt.delFromList('+i.toString()+')">从列表中清除</a>');
			$('#blackList').append(newRow);
			}
			$('#blackList tbody tr:odd').addClass("odd");
			$('#blackList tbody tr:even').addClass("even");
			$('#listContainer').find('td').width(200);
			$('.even').css('background','#FFF38F');
			$('.odd').css('background','#FFFFEE');
			$('.close-floatbox').css('color','#FFF38F');
		//$('.del_btn').bind('click',delFromList);

		}

		function initControlList()
		{
			var pageFrame='<div id="listContainer" style="height:300px;overflow-y:auto;"><div style="margin-left:100px"><table id="blackList"></table><button type="button" id="confirmChange">确定</button></div></div>'; 
			//$('#listContainer').css("height","300px");
			//$('#listContainer').css("overflow-y","auto");
			$.floatbox({content:pageFrame,fade:true});
			zipIt.blacklist=localStorage.getObject('blacklist');
			traverseList();
			$('#confirmChange').bind('click',function(){
				if(confirm("确定更改列表?")==true)
				{
				//alert("yeps");
				localStorage.setObject('blacklist',zipIt.blacklist);
				}
				else{}
			});
		}
		


			//初始化页面
		function initiatePage()
		{

			function JQ1_wait() {
			if(typeof window.jQuery == 'undefined') { window.setTimeout(JQ1_wait,100); }
			else { $ = window.jQuery; 
			initFloatBox();
			startShush();
			}
			}
			JQ1_wait();
		}
		


		function startShush()
		{
			var tempArrs=document.getElementsByTagName('a');
			var appendPoint="";
			var regexPoint=/hack\.php\?H_name=bank/;
			for(var i=0;i<tempArrs.length;i++)
			{
				var result="";
				result=regexPoint.exec(tempArrs[i].href)
				if(result)
				{
					appendPoint=tempArrs[i];
				}
			}
			$(appendPoint).after('  |  <a href="javascript:window.zipIt.listControl()">抽屉管理</a>');
			var nowURL=document.URL;
			var regexNavi1=/^http:\/\/bbs\.(9gal|9baka)\.com\/read\.php/;
			var regexNavi2=/^http:\/\/bbs\.(9gal|9baka)\.com\/thread\.php/;
			var regexNavi3=/^http:\/\/bbs\.(9gal|9baka)\.com\/profile\.php/;
			var regexNavi4=/^http:\/\/bbs\.(9gal|9baka)\.com|kf_fw_ig_renew\.php/;
			var regexNavi5=/^http:\/\/bbs\.(9gal|9baka)\.com|kf_fw_ig_my\.php/;
			if((regexNavi1.exec(nowURL)))
			{
				getAllReply();
				checkBlackListedReply();
			}
			else if((regexNavi2.exec(nowURL)))
			{
				
				getAllThreadHead();
				checkBlackListedHead();
			}
			if((regexNavi3.exec(nowURL)))
			{
				modifyProfilePage();
			}
			if((regexNavi4.exec(nowURL)))
			{
				parseTrans();
			}
			if((regexNavi5.exec(nowURL)))
			{
				parseMyItem();
			}
		}
		function parseTrans()
		{
			var ids=$('a[href*=kf_fw_ig_renew.php?lv=]');
			$.each(ids,function(i,node){
				var inPoint=$(node).parent().prev();
				var id=node.href.match(/renew\.php\?lv=(\d+)/)[1];
				var jsnode="<td><a href='javascript:zipIt.transitem("+id+");'>全部转换本级已使用道具为能量</a></td>";
				inPoint.replaceWith(jsnode);
			});
		}
		function parseMyItem()
		{
			var ids=$('a[href*=kf_fw_ig_my.php?pro=]');
			$.each(ids,function(i,node){
			var inPoint=$(node).parent().prev();
			var id=node.href.match(/my\.php\?pro=(\d+)/)[1];
			var jsnode="<td><a href='kf_fw_ig_doit.php?id="+id+"'>使用</a> | <a href='kf_fw_ig_shop.php?sell=no&id="+id+"'>交易</a></td>";
			inPoint.replaceWith(jsnode);
		});

		}
		function transitem(id)
		{
			zipIt.transQueue=[];
			zipIt.transDic={};
			zipIt.transTotal=0;
			$.get('/kf_fw_ig_renew.php?lv='+id,function(page){
				var nodes=page.match(/kf_fw_ig_my\.php\?pro=\d+/g);
				zipIt.transDic[id]=nodes.length;
				if(nodes.length>0)
				{
				for(var i=0;i < nodes.length;i++)
				{
					$.get("/"+nodes[i],function(data){
						var transButton=data.match(/(kf_fw_ig_doit\.php\?tomp.*?)\"/)[1];
						zipIt.transQueue.push(transButton);
						finishReqQueue(zipIt.transDic[id],zipIt.transQueue);
					});
				}
				}
			})
		}
		function finishReqQueue(queueLength,queue)
		{
			if(queue.length == queueLength && queueLength > 0)
			{
				$.get("/"+queue[0],function(data)
				{
					var result=data.match(/该道具已经转换为了(.*)点能量/);
					if(result)
					{
						//console.log(result[0]);
						zipIt.transTotal+=parseInt(result[1]);
						queueLength-=1;
						queue.shift();
						finishReqQueue(queueLength,queue);
					}
				});
			}
			if(queue.length==0)
			{
				alert('总共转换为能量'+zipIt.transTotal+'点');
				location.reload();	
			}
		}
		
		window.zipIt=zipIt;
		window.zipIt.initPage=initiatePage;
		window.zipIt.threads=wholeThreads;
		window.zipIt.delFromList=delFromList;
		window.zipIt.listControl=initControlList;
		window.zipIt.initPage();
		window.zipIt.userInfo=getUserInfo;
		window.zipIt.transitem=transitem;
	}
})();
